{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# python基础查漏补缺"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. 基础概念"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.1 数据类型和变量"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "I 'm \"OK\"!\n"
     ]
    }
   ],
   "source": [
    "string = 'I \\'m \\\"OK\\\"!'         # 用 \\ 对',\"进行转义可输出该字符 \n",
    "print(string)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "I am \"ok\"\n",
      "I 'm \"Ok\"!            \n",
      "Hello world!\n",
      "I 'm happy to learn python!\n"
     ]
    }
   ],
   "source": [
    "print(r'I am \"ok\"')             # r' ' 或r\" \"中间的字符串不转义 r\"\"\"字符串\"\"\"，其中\",'都可以用\n",
    "print(r\"\"\"I 'm \"Ok\"!            \n",
    "Hello world!\n",
    "I 'm happy to learn python!\"\"\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "5 >3 or 1 >3          # and,or,not运算符的优先级比大于小于号低\n",
    "5 >3 and 1 <3\n",
    "not 5 < 3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "None\n",
      "False\n",
      "inf\n"
     ]
    }
   ],
   "source": [
    "print(None)           # None是空值，不等于0      ，ctrl + d 快键键是删除该行\n",
    "print(None == 0)\n",
    "import numpy as np\n",
    "print(np.inf)         # numpy的 inf 表示无穷大"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3.0\n",
      "3.3333333333333335\n",
      "3\n",
      "1\n"
     ]
    }
   ],
   "source": [
    "print(9 / 3)            # / 除法得浮点数，// 除法后取整数， % 除法后取余数\n",
    "print(10 / 3)\n",
    "print(10 // 3)\n",
    "print(10 % 3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.2 字符串和编码"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "unicode编码统一多国语言符号，UTF-8是它的可变长形式，节约空间"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "你好python！\n"
     ]
    }
   ],
   "source": [
    "print('你好python！')    # python3是Unicode编码 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "65\n",
      "a\n"
     ]
    }
   ],
   "source": [
    "print(ord('A'))    # ord()将字符转换为整数编码\n",
    "print(chr(97))     # chr()将编码转换为字符"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'bytes'>\n",
      "<class 'str'>\n"
     ]
    }
   ],
   "source": [
    "x = b'ABC'    # bytes类型的数据\n",
    "print(type(x))\n",
    "y = 'ABC'     # str字符串类型的数据\n",
    "print(type(y))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "字符串编解码"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "b'ABC'\n",
      "b'\\xe4\\xb8\\xad\\xe6\\x96\\x87'\n"
     ]
    }
   ],
   "source": [
    "out1 = 'ABC'.encode('ascii')       # 英语可用ascii编码，汉语只能用utf-8编码,得到bytes数据\n",
    "out2 = '中文'.encode('utf-8')      \n",
    "print(out1)\n",
    "print(out2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ABC\n",
      "中文\n",
      "中\n"
     ]
    }
   ],
   "source": [
    "out1 = b'ABC'.decode('ascii')      # bytes数据解码为认识的字符\n",
    "out2 = b'\\xe4\\xb8\\xad\\xe6\\x96\\x87'.decode('utf-8')\n",
    "out3 = b'\\xe4\\xb8\\xad\\xff'.decode('utf-8', errors='ignore')  # bytes中包含错误，可使用ignore忽略\n",
    "print(out1)\n",
    "print(out2)\n",
    "print(out3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "格式化输出"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "==3  ==  1==\n",
      "3.14\n"
     ]
    }
   ],
   "source": [
    "# 1. % 格式化输出， %x 表示十六进制整数\n",
    "print('==%-3d==%3d==' % (3, 1))   \n",
    "print('%.2f' % 3.1415926)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello 小明, 成绩提高了97.23\n",
      "hello 97.23\n",
      "my name is 小明, my age is 20\n",
      "my name is 小明, my age is 20\n",
      "右对齐:*********1, 居中:****2*****, 左对齐:3*********\n",
      "二进制：1010, 八进制：12, 16进制：a, 千分位划分：123,456,789\n",
      "my name is 小明, my age is 20\n"
     ]
    }
   ],
   "source": [
    "# 2. format 格式化输出\n",
    "# 2.1 使用位置参数 0,1\n",
    "string1 = 'hello {0}, 成绩提高了{1:.2f}'.format('小明', 97.235)\n",
    "print(string1)\n",
    "string2 = 'hello {:^.2f}'.format(97.233)\n",
    "print(string2)\n",
    "\n",
    "# 2.2 使用关键字参数\n",
    "dictionary = {'name':'小明', 'age':20}\n",
    "string3 = 'my name is {name}, my age is {age}'.format(name='小明', age=20)\n",
    "string4 = 'my name is {name}, my age is {age}'.format(**dictionary)\n",
    "print(string3)\n",
    "print(string3)\n",
    "\n",
    "# 2.3 使用填充与格式化\n",
    "string5 = '右对齐:{0:*>10}, 居中:{1:*^10}, 左对齐:{2:*<10}'.format(1,2,3)  # :左边的表示位置，10表示宽度\n",
    "print(string5)\n",
    "\n",
    "# 2.4 精度与进制\n",
    "string6 = '{0:b}'.format(10)         # 二进制\n",
    "string7 = '{0:o}'.format(10)         # 八进制\n",
    "string8 = '{0:x}'.format(10)         # 16进制\n",
    "string9 = '{:,}'.format(123456789)   # 千分位格式化\n",
    "print('二进制：%s, 八进制：%s, 16进制：%s, 千分位划分：%s'% (string6,string7,string8,string9))\n",
    "\n",
    "# 2.5 使用索引\n",
    "info = ['小明', 20]\n",
    "string10 = 'my name is {0[0]}, my age is {0[1]}'.format(info)\n",
    "print(string10)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "字符串常用操作"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1.查找python字符串在原字符串中开始位置: 6\n",
      "2.查找thon字符串在原字符串中开始位置: 8\n",
      "3.字符o出现的次数: 4\n",
      "4.替换字符o后字符串: hell0 pyth0n, hello world!     |  原字符串不变: hello python, hello world!\n",
      "5.切分后的结果: ['hello', 'python,', 'hello world!']  |  原字符串不变: hello python, hello world!\n",
      "6.字符串he是开头,是结尾: True False\n",
      "7.左对齐: hello python, hello world!---\n",
      "  右对齐: ---hello python, hello world!\n",
      "  居中: --hello python, hello world!-\n",
      "8.字符串: --hello python, hello world!--\n",
      "  去除左边指定字符: hello python, hello world!--\n",
      "  去除右边指定字符: --hello python, hello world!\n",
      "  去除两边指定字符: hello python, hello world!\n",
      "9.使用的连接符: -\n",
      "  列表连接的结果: hello-python-hello-python\n"
     ]
    }
   ],
   "source": [
    "mystr = 'hello python, hello world!'\n",
    "# 1. find(str, start=0, end=len(mystr))查找str字符串在原字符串中首次出现位置,如果没找到返回1\n",
    "out = mystr.find('python',0,12)    \n",
    "print('1.查找python字符串在原字符串中开始位置:',out)\n",
    "# 2. index(str, start=0, end=len(mystr))与find()函数一样，不同没找到抛出异常ValueError\n",
    "out = mystr.index('thon')\n",
    "print('2.查找thon字符串在原字符串中开始位置:',out)\n",
    "# 3. count(str, start=0, end=len(mystr))返回str在star和end之间 在mystr里面出现的次数\n",
    "out = mystr.count('o')\n",
    "print('3.字符o出现的次数:', out)\n",
    "# 4. replace(str1, str2, mystr.count(str1))把mystr中的str1替换成str2，若果count指定，则替换不超过count次\n",
    "# 原字符串不变\n",
    "out = mystr.replace('o', '0', 2)    # 这里只指定2次，所以只有两个地方被替换\n",
    "print('4.替换字符o后字符串:', out, end='     |  ')\n",
    "print('原字符串不变:',mystr)\n",
    "# 5. split(str, maxsplit) 以str为分隔符切片mystr，如果maxsplit有指定值，则使用maxsplit个str切分\n",
    "out = mystr.split(' ', 2)\n",
    "print('5.切分后的结果:', out, end='  |  ')  # 这里使用2个空格切分，得到3个字符串的列表\n",
    "print('原字符串不变:',mystr)\n",
    "# 6. mystr.startswith(obj) 检查字符串是否以obj开头，是则返回True，否则返回False. \n",
    "# mystr.endswith(obj) 检查字符串是否以obj结束，是则返回True，否则返回False. \n",
    "out = mystr.startswith('he')\n",
    "out2 = mystr.endswith('he')\n",
    "print('6.字符串he是开头,是结尾:', out, out2 )\n",
    "# 7. mystr.ljust(width) 返回一个原字符串左对齐，并使用空格填充至长度width的新字符串. \n",
    "# mystr.rjust(width)    返回一个原字符串右对齐，并使用空格填充至长度width的新字符串. \n",
    "# mystr.center(width)  返回一个原字符串居中，并使用空格填充至长度width的新字符串\n",
    "out = mystr.ljust(29,'-')      # 用' '补齐空缺，默认使用空格\n",
    "out1 = mystr.rjust(29,'-')\n",
    "out2 = mystr.center(29,'-')\n",
    "print('7.左对齐:', out)\n",
    "print('  右对齐:', out1)\n",
    "print('  居中:', out2)\n",
    "# 8.mystr.lstrip()删除mystr字符串左端的空白字符.\n",
    "# mystr.rstrip()删除mystr字符串末尾的空白字符.\n",
    "# mystr.strip()删除mystr字符串两端的空白字符.\n",
    "mystr = '--' + mystr + '--'\n",
    "out = mystr.lstrip('-')\n",
    "out1 = mystr.rstrip('-')\n",
    "out2 = mystr.strip('-')\n",
    "print('8.字符串:', mystr)\n",
    "print('  去除左边指定字符:', out)\n",
    "print('  去除右边指定字符:', out1)\n",
    "print('  去除两边指定字符:', out2)\n",
    "# 9. str.join(mystr) mystr中每个字符后面插入str, 构造出一个新的字符串连接列表\n",
    "mystr='-'\n",
    "mylist = ['hello','python','hello','python']\n",
    "out = mystr.join(mylist)\n",
    "print('9.使用的连接符:', mystr)\n",
    "print('  列表连接的结果:', out)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.3 list和tuple"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "list操作"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['Michael', 'Jack', 'Bob']\n",
      "['Michael', 'Jack', 'Bob', 'Adam']\n",
      "['Michael', 'Jack', 'Tracy', 'Bob', 'Adam']\n",
      "['Michael', 'Jack', 'Tracy', 'Bob']\n",
      "['Michael', 'Tracy', 'Bob']\n",
      "['Michael', 123, 'Bob']\n"
     ]
    }
   ],
   "source": [
    "classmates = ['Michael', 'Jack', 'Bob']\n",
    "print(classmates)\n",
    "classmates.append('Adam')     # append(element)在末尾添加元素\n",
    "print(classmates)\n",
    "classmates.insert(2, 'Tracy') # insert(index, element)在index位置插入element\n",
    "print(classmates)\n",
    "classmates.pop()              # pop()删除末尾元素\n",
    "print(classmates)\n",
    "classmates.pop(1)             # pop(index)删除index位置的元素\n",
    "print(classmates)\n",
    "classmates[1] = 123           # classmates[index]可以赋值替换\n",
    "print(classmates)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 3, 4, 1, 5, 1]\n",
      "number 1 counts : 3\n",
      "1 index: 5\n",
      "[1, 2, 3, 4, 1, 5, 1]\n",
      "[2, 3, 4, 1, 5, 1]\n",
      "[1, 5, 1, 4, 3, 2]\n",
      "[1, 1, 2, 3, 4, 5]\n",
      "[1, 1, 2, 3, 4, 5, '123', 'python']\n"
     ]
    }
   ],
   "source": [
    "list1 = [1,2,3,4,1,5,1]\n",
    "print(list1)\n",
    "counts = list1.count(1)              # count(element)统计element出现的次数\n",
    "print('number 1 counts :', counts)\n",
    "index = list1.index(5)               # index(element)查找element的索引号，如果有多个只返回第一个\n",
    "print('1 index:', index)\n",
    "print(list1)\n",
    "list1.remove(1)                      # remove(element)删除列表中首次出现的element\n",
    "print(list1)\n",
    "list1.reverse()                      # reverse()列表反向\n",
    "print(list1)\n",
    "list1.sort()                         # sort()列表排序，reverse = True降序\n",
    "print(list1)\n",
    "list1.extend(['123','python'])       # extend(list_new)连接列表，与 + 功能相同\n",
    "print(list1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "False\n",
      "7\n",
      "-1\n",
      "4\n",
      "0\n"
     ]
    }
   ],
   "source": [
    "import operator\n",
    "print(operator.eq(2,3))          # 比较两个元素是否相等\n",
    "print(max([1,2,3,4,1,5,7,2]))    # 取最大值和最小值\n",
    "print(min([7,5,3,2,6,-1,6]))\n",
    "print(len([1,2,4,6]))            # 返回长度\n",
    "print(len([]))                   # 空列表长度为0"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**list列表生成**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[2, 3, 4, 5, 6, 7, 8]\n"
     ]
    }
   ],
   "source": [
    "test_list = [1,2,3,4,5,6,7]            # 列表同样适用\n",
    "output_list = [s+1 for s in test_list]\n",
    "print(output_list)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "tuple元素不可变，读取操作与list相同"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(1, 2)\n",
      "<class 'tuple'>\n",
      "()\n",
      "1\n",
      "<class 'int'>\n",
      "(1,)\n",
      "<class 'tuple'>\n"
     ]
    }
   ],
   "source": [
    "t1 = (1,2)\n",
    "print(t1)\n",
    "print(type(t1))\n",
    "t2 = ()\n",
    "print(t2)\n",
    "#----------------------\n",
    "t3 = (1)\n",
    "print(t3)\n",
    "print(type(t3))\n",
    "t4 = (1,)                #为了避免与整数冲突，单个元素的元组tuple使用 , 隔开\n",
    "print(t4)\n",
    "print(type(t4))\n",
    "#---------------------"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.4 判断和循环"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "please input a number:123\n",
      "this is a positive number which is more than 100.\n"
     ]
    }
   ],
   "source": [
    "input_str = input('please input a number:')   # 读取得到一个str类型数据\n",
    "input_num = int(input_str) \n",
    "if input_num < 0:\n",
    "    print('this is a negative number.')\n",
    "elif input_num < 100:\n",
    "    print('this is a positive number which is less than 100.')\n",
    "else:\n",
    "    print('this is a positive number which is more than 100.')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "i= 0\n",
      "i= 1\n",
      "i= 2\n",
      "i= 3\n",
      "i= 4\n",
      "i= 5\n",
      "i= 6\n",
      "-------------\n",
      "i=0,j=1\n",
      "i=1,j=2\n",
      "i=2,j=3\n",
      "-------------\n",
      "i= 0\n",
      "i= 1\n",
      "i= 2\n"
     ]
    }
   ],
   "source": [
    "# for循环访问列表\n",
    "for i in range(7):\n",
    "    print('i=',i)\n",
    "print('-------------')\n",
    "for i,v in enumerate([1,2,3]):      # i:index, v:value\n",
    "    print('i={0},j={1}'.format(i,v))\n",
    "print('-------------')\n",
    "\n",
    "# while循环处理\n",
    "i = 0\n",
    "while i < 3:\n",
    "    print('i=', i)\n",
    "    i += 1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**break退出整个循环，continue结束当前本轮循环，开始下一次循环**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.5 dict和set"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "字典的初始化"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1.使用{}初始化: {'a': 1, 2: 'b', 'c': '3'}\n",
      "2.使用元素为2元组的列表初始化: {'a': 1, 2: 'b', 'c': '3'}\n",
      "3.使用zip组合数据转换为列表: [(1, 'a'), (2, 'b'), (3, 'c')]\n",
      "  使用zip组合数据转换为字典: {1: 'a', 2: 'b', 3: 'c'}  |  zip对象只迭代一次,第2次迭代结果: {}\n"
     ]
    }
   ],
   "source": [
    "out = {'a':1, 2:'b', 'c':'3'}\n",
    "print('1.使用{}初始化:', out)\n",
    "out = dict([('a',1), (2,'b'), ['c','3']])   # 必须是列表\n",
    "print('2.使用元素为2元组的列表初始化:', out)\n",
    "zip_out = zip([1,2,3],['a','b','c']) \n",
    "print('3.使用zip组合数据转换为列表:', list(zip_out))\n",
    "zip_out1 = zip([1,2,3],['a','b','c'])     # zip\n",
    "print('  使用zip组合数据转换为字典:', dict(zip_out1), end='  |')\n",
    "print('  zip对象只迭代一次,第2次迭代结果:', dict(zip_out1))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "字典的迭代"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1.使用循环访问字典\n",
      " value值: 1\n",
      " value值: b\n",
      " value值: 3\n",
      "2.使用items()进行迭代: dict_items([('a', 1), (2, 'b'), ('c', '3')])\n",
      "3.使用列表生成的方式访问字典: [('a', 1), (2, 'b'), ('c', '3')]\n",
      "4.使用字典生成的方式访问: {'a': 1, 2: 'b', 'c': '3'}\n"
     ]
    }
   ],
   "source": [
    "dictionary  = {'a':1, 2:'b', 'c':'3'}\n",
    "print('1.使用循环访问字典')\n",
    "for k in dictionary:\n",
    "    print(' value值:',dictionary[k])    \n",
    "out = dictionary.items()\n",
    "print('2.使用items()进行迭代:', out)\n",
    "\n",
    "out = [(k,v) for k,v in dictionary.items()]  # 生成列表，可以对key-value对进行操作\n",
    "print('3.使用列表生成的方式访问字典:', out)\n",
    "out = {k:v for k,v in dictionary.items()}    # 生成字典\n",
    "print('4.使用字典生成的方式访问:', out)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "字典的内置函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1.原字典: {'Name': '小明', 'age': 25}\n",
      "  删除Name键值: {'age': 25}\n",
      "2.清空字典: {}\n",
      "3.删除字典变量: NameError:name 'mydict' is not defined\n"
     ]
    }
   ],
   "source": [
    "# 1. clear() 删除字典内所有元素\n",
    "mydict = {'Name':'小明', 'age':25}\n",
    "print('1.原字典:', mydict)\n",
    "del mydict['Name'] # 删除键 'Name'       \n",
    "print('  删除Name键值:', mydict)\n",
    "mydict.clear()     # 清空字典\n",
    "print('2.清空字典:', mydict)\n",
    "del mydict         # 删除字典\n",
    "try:\n",
    "    print(mydict)\n",
    "except NameError as err:\n",
    "    print('3.删除字典变量:', 'NameError:%s' % err)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1.原字典: {'a': 1, 2: 'b', 'c': '3'}\n",
      "2.浅复制的结果: {'a': 7, 2: 'b', 'c': '3'} | 原字典不变: {'a': 1, 2: 'b', 'c': '3'}\n",
      "{'a': 1, 2: 'change', 'c': '3'}\n",
      "3.创建seq序列为键值的字典: {'name': 7, 'age': 7, 'sex': 7}\n",
      "4.键a的值为: 1\n",
      "  键d的值为: d is not in this dict\n",
      "5.键a在字典中: True\n",
      "6.返回字典的变量(key,value): dict_items([('a', 1), (2, 'change'), ('c', '3')])\n",
      "7.返回字典中的所有键: dict_keys(['a', 2, 'c'])\n",
      "8.添加键为d的值: {'a': 1, 2: 'change', 'c': '3', 'd': 'python'}\n",
      "9.两个字典连接的结果: {'a': 1, 2: 'change', 'c': '3', 'd': 'python', 'name': '小明'}\n",
      "10.返回字典中的所有值: dict_values([1, 'change', '3', 'python', '小明'])\n",
      "11.当前字典为: {'a': 1, 2: 'change', 'c': '3', 'd': 'python', 'name': '小明'}\n",
      "   处理后的字典: {'a': 1, 2: 'change', 'c': '3', 'd': 'python'}\n",
      "   删除的值: 小明\n",
      "12.当前字典为: {'a': 1, 2: 'change', 'c': '3', 'd': 'python'}\n",
      "   处理后的字典: {'a': 1, 2: 'change', 'c': '3'}\n",
      "   删除的键值对: ('d', 'python')\n"
     ]
    }
   ],
   "source": [
    "mydict = {'a':1, 2:'b', 'c':'3'}\n",
    "print('1.原字典:', mydict)\n",
    "# 2. copy() 返回一个字典的浅复制\n",
    "mydict1 = mydict.copy()\n",
    "mydict1['a'] = 7\n",
    "print('2.浅复制的结果:', mydict1, end=' | ')\n",
    "print('原字典不变:', mydict)\n",
    "# 3. fromkeys(seq[, value]) 创建一个新字典，以序列seq中元素做字典的键，val为字典所有键对应的初始值\n",
    "seq = ['name', 'age', 'sex']\n",
    "out = dict.fromkeys(seq, 7)  # {}.fromkeys(seq, 7), 7为默认的值\n",
    "print('3.创建seq序列为键值的字典:', out)\n",
    "# 4. get(key, default=None) 返回指定键的值，如果值不在字典中返回default值\n",
    "out = mydict.get('a')\n",
    "print('4.键a的值为:', out)\n",
    "out = mydict.get('d', 'd is not in this dict')   # 如果不含该键，则返回None\n",
    "print('  键d的值为:', out)\n",
    "# 5. key in dict 如果键在字典dict里返回true，否则返回false\n",
    "print('5.键a在字典中:', 'a' in mydict)\n",
    "# 6. items() 以列表返回可遍历的(键, 值) 元组数组\n",
    "print('6.返回字典的变量(key,value):', mydict.items())\n",
    "# 7. keys() 以列表返回一个字典所有的键\n",
    "print('7.返回字典中的所有键:', mydict.keys())\n",
    "# 8. setdefault(key, default=None) 和get()类似, 但如果键不存在于字典中，将会添加键并将值设为default\n",
    "out = mydict.setdefault('d', 'python')\n",
    "print('8.添加键为d的值:', mydict)\n",
    "# 9. update(dict2) 把字典dict2的键/值对更新到dict里\n",
    "mydict1 = {'name':'小明'}\n",
    "mydict.update(mydict1)\n",
    "print('9.两个字典连接的结果:',mydict)\n",
    "# 10. values() 以列表返回字典中的所有值\n",
    "print('10.返回字典中的所有值:', mydict.values())\n",
    "# 11. pop(key[,default]) 删除字典给定键 key所对应的值，返回值为被删除的值\n",
    "# key值必须给出。如果没有该键则返回default值。\n",
    "print('11.当前字典为:', mydict)\n",
    "out = mydict.pop('name', 'nonsense key')\n",
    "print('   处理后的字典:', mydict)\n",
    "print('   删除的值:', out)\n",
    "# 12. popitem() 随机返回并删除字典中的一对键和值(一般删除末尾对)\n",
    "print('12.当前字典为:', mydict)\n",
    "out = mydict.popitem()\n",
    "print('   处理后的字典:', mydict)\n",
    "print('   删除的键值对:', out)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "集合的操作"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1.使用set()创建无序不重复集合: {1, 2, 3}\n",
      "2.使用{}创建集合: {1, 2, 3, 5}\n",
      "3.两个集合分别为: {1, 2, 3, 5} {3, 4, 5}\n",
      "  集合交集: {3, 5}\n",
      "  集合并集: {1, 2, 3, 4, 5}\n",
      "  1集合中去除与2集合相交的元素: {1, 2}\n",
      "  1,2集合交集外的元素集合: {1, 2, 4}\n",
      "4.处理字符串去重的结果: {'h', 'e', 'p', 'n', 'o', 't', 'l', 'y', ' '}\n",
      "  创建单个元素为字符串的集合: {'hello'}\n"
     ]
    }
   ],
   "source": [
    "myset = set([1,1,2,2,3,3])\n",
    "print('1.使用set()创建无序不重复集合:',myset)\n",
    "myset = {1,2,3,5,3,5,5,}\n",
    "print('2.使用{}创建集合:', myset)\n",
    "myset1 = set([3,4,5])\n",
    "print('3.两个集合分别为:', myset, myset1)\n",
    "print('  集合交集:', myset & myset1)\n",
    "print('  集合并集:', myset | myset1)\n",
    "print('  1集合中去除与2集合相交的元素:', myset - myset1)\n",
    "print('  1,2集合交集外的元素集合:', myset ^ myset1)\n",
    "myset = set('hello python')\n",
    "print('4.处理字符串去重的结果:',myset)\n",
    "myset = set(('hello',))          # 需要加 , 否则把它拆分为单个字符\n",
    "print('  创建单个元素为字符串的集合:', myset)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1.原集合: {1, 2, 3, 4}\n",
      "2.add()方法增加新的元素后: {1, 2, 3, 4, 'python'}\n",
      "3.update()方法新增元素: {1, 2, 3, 4, 'b', 'hello', 'c', 'python', 2333, 'a'}\n",
      "4.remove()方法删除新增的元素后: {1, 2, 3, 4, 'b', 'hello', 'c', 2333, 'a'}\n",
      "5.discard()方法删除元素: {1, 2, 3, 4, 'b', 'c', 2333, 'a'}\n",
      "6.pop()方法随机删除元素: {2, 3, 4, 'b', 'c', 2333, 'a'}\n",
      "7.clear()方法清空集合: set()\n"
     ]
    }
   ],
   "source": [
    "myset = set([1,2,3,4])\n",
    "print('1.原集合:', myset)\n",
    "myset.add('python')\n",
    "print('2.add()方法增加新的元素后:', myset)\n",
    "myset.update([1,2],['hello'], 'abc',{2333})\n",
    "print('3.update()方法新增元素:', myset)\n",
    "myset.remove('python')\n",
    "print('4.remove()方法删除新增的元素后:', myset)\n",
    "myset.discard('hello')     # 如果不存在，不会报错\n",
    "print('5.discard()方法删除元素:', myset)\n",
    "myset.pop()\n",
    "print('6.pop()方法随机删除元素:', myset)\n",
    "myset.clear()\n",
    "print('7.clear()方法清空集合:', myset)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**集合推导式，类似于列表和字典**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1.集合的推导式 {'c', 'b'}\n"
     ]
    }
   ],
   "source": [
    "out = {i for i in 'abcabcabc' if i not in 'a'}\n",
    "print('1.集合的推导式', out)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
